package com.longg.service.impl;

import com.longg.dao.DeptDao;
import com.longg.dao.UserDao;
import com.longg.model.Dept;
import com.longg.model.User;
import com.longg.service.IUserService;
import com.longg.utils.CodeUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServiceImpl implements IUserService {
    private UserDao dao = new UserDao();
    private DeptDao deptDao = new DeptDao();

    @Override
    public User findByName(String username) {
        User user = null;
        List<User> userList = dao.findByCol("username", username);
        if(!userList.isEmpty() && null != userList){
            user = userList.get(0);
        }
        return user;
    }

    @Override
    public List<User> findByEmail(String email) {
        List<User> userList = dao.findByCol("email", email);
        return userList;
    }

    @Override
    public List<User> findByEmailOrName(String email, String username) {
        Map<String,Object> colMap = new HashMap<>();
        colMap.put("email",email);
        colMap.put("username",username);
        return dao.findByCols("or",colMap);
    }

    @Override
    public boolean addUser(User user) {
        int i = dao.save(user);
        if(0 == i){
            return false;
        }
        return true;
    }

    @Override
    public String sendCode(String email) {
        return CodeUtil.sendCode(4,email);
    }

    @Override
    public boolean resetPassword(User user) {
        int i = dao.update(user);
        if(0 == i){
            return false;
        }
        return true;
    }

    @Override
    public Map<String, Object> getUserBaseInfo(String username) {
        return dao.getUserBaseInfo(username);
    }

    @Override
    public Map<String, Object> getUserInfo(String id) {
        Map<String, Object> userInfo = dao.getUserInfo(Integer.parseInt(id));
        return userInfo;
    }

    @Override
    public boolean updateInfo(int id, String secret,String deptName) {
        List<Dept> deptList = deptDao.findByCol("name", deptName);
        User user = dao.findById(id);
        user.setIsSecret(secret);
        user.setDeptId(deptList.get(0).getId());
        int update = dao.update(user);
        return update > 0;
    }

    @Override
    public List<Map<String, Object>> findUsersByPage(int page,int id,String name) {
        return dao.findUsersByPage(page,id,name);
    }
}
